#include "ExtPROM.h"


void ExtPROM::init(int ssPin){
	slaveSelectPin=ssPin;
	SPI.begin();
	SPI.setBitOrder(MSBFIRST);
	SPI.setClockDivider(SPI_CLOCK_DIV4);
	SPI.setDataMode(SPI_MODE0);
	SPI.detachInterrupt();
	delay(10);
	digitalWrite(slaveSelectPin, LOW);
	SPI.transfer(WREN);
	digitalWrite(slaveSelectPin, HIGH);
	delay(10);
}

uint8_t ExtPROM::readStatus(){
	volatile uint8_t data;

	digitalWrite(slaveSelectPin, LOW);
	SPI.transfer(RDSR); //transmit readStatusRegister opcode
	data = SPI.transfer(0xFF); //get data byte
	digitalWrite(slaveSelectPin, HIGH);
	delay(10);
	return data;
}

void ExtPROM::writeLogPage(uint16_t address, LogPage writePage){
	LogBuff outBuff = SpiLOG.PageToBuff(writePage);

#ifdef tst_WR_VERBOSE
	Serial.print("ADR: ");
	Serial.print((uint8_t)(address>>8));
	Serial.println((uint8_t)address);
	for(int p=0; p<def_LOG_RECS_PER_PAGE; p++){
		for(int q=0; q<def_LOG_REC_LEN; q++){
			Serial.print(outBuff.data[(p*def_LOG_REC_LEN)+q]); //write data byte
			Serial.print(", ");
		}
		Serial.println();
		delay(1000);
		Serial.println();
	}
#endif

	uint8_t status = SpiPROM.readStatus();


	while((status&0x01)==0x01){		//are you ready?
		status=SpiPROM.readStatus();
		numRdyWrHolds++;
	}

	digitalWrite(slaveSelectPin,LOW);
	SPI.transfer(WREN);
  	digitalWrite(slaveSelectPin, HIGH);

	while((status&0x02)!=0x02){		//ready to write?
		status=SpiPROM.readStatus();
		numWrenWrHolds++;
	}

	digitalWrite(slaveSelectPin,LOW);
	SPI.transfer(WRITE); //write instruction
	SPI.transfer((uint8_t)(address>>8));   //send MSByte address first
	SPI.transfer((uint8_t)address);      //send LSByte address

	for(int i=0; i<def_LOG_PAGE_LEN; i++){
			SPI.transfer(outBuff.data[i]); //write data byte
	}
	digitalWrite(slaveSelectPin, HIGH);
}

		
LogPage ExtPROM::readLogPage(uint16_t address){

	LogBuff inBuff;

	uint8_t status = SpiPROM.readStatus();

	while((status&0x01)==0x01){		//are you ready?
		status=SpiPROM.readStatus();
		numReadHolds++;
	}

	digitalWrite(slaveSelectPin, LOW);
	SPI.transfer(READ); //transmit read opcode

	SPI.transfer((uint8_t)(address>>8));   //send MSByte address first
	SPI.transfer((uint8_t)address);      //send LSByte address


	for(int i=0; i<def_LOG_PAGE_LEN; i++){
		inBuff.data[i] = SPI.transfer(0xff); //read
	}
	digitalWrite(slaveSelectPin,HIGH); //release chip

#ifdef tst_RD_VERBOSE
	Serial.print("ADR: ");
	Serial.print((uint8_t)(address>>8));
	Serial.println((uint8_t)address);
	
	for(int q=0; q<def_LOG_PAGE_LEN; q++){
		if((q%32)==0)
			Serial.println();
		Serial.print(inBuff.data[q]); //write data byte
		Serial.print(", ");
	}
	Serial.println();


#endif

	return SpiLOG.BuffToPage(inBuff);
}









































ExtPROM SpiPROM;